package com.pmt.feedplayer.controller

import com.pmt.feedplayer.core.AudioExtractor
import com.pmt.feedplayer.core.SpeechRecognizer
import com.pmt.feedplayer.core.Translator
import com.pmt.feedplayer.core.SubtitleManager
import com.pmt.feedplayer.data.TranslationResult
import com.pmt.feedplayer.data.TranslationState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * 翻译控制器
 * 管理实时视频音频翻译的状态和业务逻辑
 */
class TranslationController(
    private val audioExtractor: AudioExtractor,
    private val speechRecognizer: SpeechRecognizer,
    private val translator: Translator,
    private val subtitleManager: SubtitleManager,
    private val scope: CoroutineScope
) {
    // 状态管理
    private val _translationState = MutableStateFlow(TranslationState.IDLE)
    private val _isTranslationEnabled = MutableStateFlow(false)
    private val _currentSubtitle = MutableStateFlow("\n")
    private val _subtitleHistory = MutableStateFlow(listOf<TranslationResult>())
    private val _translationLanguage = MutableStateFlow(Pair("ja", "zh")) // 默认日语转中文
    
    // 对外暴露的只读状态
    val translationState = _translationState.asStateFlow()
    val isTranslationEnabled = _isTranslationEnabled.asStateFlow()
    val currentSubtitle = _currentSubtitle.asStateFlow()
    val subtitleHistory = _subtitleHistory.asStateFlow()
    val translationLanguage = _translationLanguage.asStateFlow()
    
    init {
        // 监听翻译结果
        scope.launch {
            subtitleManager.translationResults.collect {
                updateSubtitle(it)
            }
        }
    }
    
    /**
     * 开始翻译过程
     */
    fun startTranslation(videoUrl: String) {
        if (_isTranslationEnabled.value) {
            _translationState.value = TranslationState.STARTING
            
            // 启动音频提取和处理流程
            scope.launch {
                try {
                    val audioFlow = audioExtractor.extractAudio(videoUrl)
                    processAudioStream(audioFlow)
                } catch (e: Exception) {
                    _translationState.value = TranslationState.ERROR
                    println("Translation error: ${e.message}")
                }
            }
        }
    }
    
    /**
     * 停止翻译
     */
    fun stopTranslation() {
        _translationState.value = TranslationState.STOPPED
        audioExtractor.stop()
        speechRecognizer.stop()
        translator.stop()
        _currentSubtitle.value = "\n"
    }
    
    /**
     * 切换翻译功能
     */
    fun toggleTranslation() {
        _isTranslationEnabled.value = !_isTranslationEnabled.value
        if (!_isTranslationEnabled.value) {
            stopTranslation()
        }
    }
    
    /**
     * 设置翻译语言对
     */
    fun setTranslationLanguages(sourceLang: String, targetLang: String) {
        _translationLanguage.value = Pair(sourceLang, targetLang)
    }
    
    /**
     * 处理音频流
     */
    private suspend fun processAudioStream(audioFlow: Flow<ByteArray>) {
        _translationState.value = TranslationState.TRANSLATING
        
        // 处理音频流，进行语音识别和翻译
        audioFlow
            .buffer() // 使用缓冲提高性能
            .collect {
                try {
                    // 1. 语音识别
                    val recognizedText = speechRecognizer.recognize(it)
                    if (recognizedText.isNotEmpty()) {
                        // 2. 文本翻译
                        val (sourceLang, targetLang) = _translationLanguage.value
                        val translatedText = translator.translate(
                            recognizedText,
                            sourceLang,
                            targetLang
                        )
                        
                        // 3. 创建翻译结果并更新字幕
                        val result = TranslationResult(
                            originalText = recognizedText,
                            translatedText = translatedText,
                            timestamp = System.currentTimeMillis()
                        )
                        
                        // 更新字幕管理器
                        subtitleManager.addTranslationResult(result)
                    }
                } catch (e: Exception) {
                    println("Error processing audio: ${e.message}")
                    // 继续处理，不中断整个流程
                }
            }
    }
    
    /**
     * 更新当前显示的字幕
     */
    private fun updateSubtitle(result: TranslationResult) {
        // 更新当前字幕
        _currentSubtitle.value = result.translatedText
        
        // 更新字幕历史（保留最近10条记录）
        _subtitleHistory.value = (_subtitleHistory.value + result).takeLast(10)
    }
    
    /**
     * 获取完整的字幕历史
     */
    fun getFullSubtitleHistory(): List<TranslationResult> {
        return subtitleHistory.value
    }
}